const Router = require('koa-router');
const User = require('../dbs/models/user.js');
const passport = require('../utils/passport');
const log4js = require('koa-log4');
const logger = log4js.getLogger('user');

const router = new Router({
  prefix: '/user' //路由前缀
});

// 获取用户信息
router.get('/getUserInfo', async (ctx) => {
  // 判断用户是否登录，passport内置
  if (ctx.isAuthenticated()) {
    const {
      _id
    } = ctx.session.passport.user;
    const result = await User.findById(_id).catch(err => {
      throw (new Error('用户信息查询失败'), 500)
    });
    const {
      password,
      ...other
    } = result._doc;
    ctx.app.emit('success', {
      data: {
        ...other
      }
    }, ctx);
  } else {
    ctx.app.emit('success', {
      status: 0,
      msg: '用户未登录'
    }, ctx);
  }
});

//注册
router.post('/signup', async (ctx) => {
  //校验session
  const {
    setCaptcha,
    setSmsCode
  } = ctx.session;
  let {
    username,
    mobile,
    password,
    captcha,
    smsCode,
  } = ctx.request.body;
  logger.info(setCaptcha, '===>captcha');
  if (setCaptcha !== captcha.toLowerCase()) {
    ctx.app.emit('success', {
      status: 0,
      msg: '图片验证码错误'
    }, ctx);
    return;
  }
  if (setSmsCode !== smsCode) {
    ctx.app.emit('success', {
      status: 0,
      msg: '短信验证码错误'
    }, ctx);
    return;
  }
  let findUser = await User.find({
    username
  });
  let findMobile = await User.find({
    mobile
  });
  if (findUser.length) {
    ctx.app.emit('success', {
      status: 0,
      msg: '该用户已被注册'
    }, ctx);
    return;
  }
  if (findMobile.length) {
    ctx.app.emit('success', {
      status: 0,
      msg: '该手机号已被注册'
    }, ctx);
    return;
  }
  //新建用户
  let newUser = await User.create({
    username,
    password,
    mobile
  });

  if (newUser) {
    ctx.app.emit('success', {
      data: {
        username,
        mobile
      }
    }, ctx)
  } else {
    ctx.throw(new Error('新建用户失败'), 500);
  }
});
//手机号验证码登录
router.post('/phone/signin', async (ctx) => {

});
// 账号密码登录
router.post('/password/signin', async (ctx) => {
  // 本地登录
  return passport.authenticate('local', function (err, user, info, status) {
    if (err) {
      ctx.throw(new Error('权限校验失败'), 500)
    } else {
      if (user) {
        const {
          password,
          ...other
        } = user._doc
        ctx.app.emit('success', {
          data: {
            ...other
          }
        }, ctx)
        // Passport中间件带的ctx.login
        return ctx.login(user._doc);
      } else {
        ctx.app.emit('success', {
          status: 0,
          msg: info
        })
      }
    }
  })(ctx)
});

//退出登录
router.get('/exit', async (ctx) => {
  await ctx.logout();
  if (!ctx.isAuthenticated()) {
    ctx.body = {
      status: 200,
      msg: '退出登录'
    }
  } else {
    ctx.body = {
      code: -1
    }
  }
});

module.exports = router;
